<template>
    <div class="app-container"
         id="mmv-page"
         v-loading="loading">
        <mmv-title :title="`车型：${modelInfo}`"></mmv-title>
        <el-button @click="clearEdit">一键清除</el-button>
        <el-calendar v-model="value">
            <template slot="dateCell"
                      slot-scope="{date, data}">
                <div class="rili-wrap"
                     :class="{'is-selected':data.isSelected,aaaaaa:isEditaaaaaa(date)}"
                     style="padding:8px;height: 100%;">
                    <div class="rili-day">{{ data.day.split('-').slice(1).join('-') }}</div>
                    <div class="rili-price-wrap">
                        <el-input-number v-if="isShowEdit(data, date)"
                                         v-model="nowPrice"
                                         size="mini"
                                         :min="0"
                                         controls-position="right"
                                         style="width: 100px;"></el-input-number>
                        <div v-else>￥{{superMmv(date, rilijiage[date.getDay()])}}</div>
                        <div v-if="isShowEdit(data, date)"
                             class="el-icon-check1"
                             style="margin-left:5px;font-size:12px"
                             @click="okEdit(date)">确定</div>
                        <div v-else
                             class="el-icon-edit"
                             style="margin-left:5px;font-size:16px"
                             @click="changeEdit(date)"></div>
                        <div v-if="isEditaaaaaa(date)"
                             class="el-icon-refresh-left"
                             style="margin-left:5px;font-size:16px"
                             @click="removeEdit(date)"></div>
                    </div>
                </div>
            </template>
        </el-calendar>

        <el-form v-if="false"
                 label-width="130px"
                 size="mini">
            <el-form-item label="请选择特殊日">
                <el-button icon="el-icon-plus"
                           size="mini"
                           type="primary"
                           @click="addTeshuri()">新增特殊日</el-button>
            </el-form-item>
            <br>
            <MmvTable v-show="specialDayList.length"
                      :list="specialDayList"
                      @close="onRemoveSpecialDay"></MmvTable>
        </el-form>
    </div>
</template>

<script>
import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import * as planApi from "@/api/plan/plan";
import map from 'lodash/map';
import forEach from 'lodash/forEach';
import MmvTable from './components/mmv-table.vue'
import _ from "lodash"
import MmvUploadImage from '../components/mmv-upload-image.vue'
import * as Utils from '@/utils'

export default {
    components: {
        MmvTitle,
        MmvTable,
        MmvUploadImage,
    },
    dicts: [
        'car_model_list_classification',
        'car_model_luxury_classification',
        'car_model_label',
        'operating_classification',
        'business_classification',
        'car_model_config_list'
    ],
    props: {
        planId: String,
        form: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            deposit: 0,
            weeksPrice: 0, // 周内价格
            weekendPrice: 0, // 周末价格
            //
            prevEdit: null,
            nowPrice: 0,
            nowEdit: null,
            loading: false,
            showchexing: false,
            planName: '', // 车价名称
            //
            configurationId: '', // 品牌车系车型
            modelId: '',
            modelName: '',
            modelInfo: '',
            upcoverImage: '',
            detailsImage: [],
            modelConfig: [],
            //
            label: [],
            operatingClassification: '',
            //
            isSetMeal: 2, // 是否需要套餐车价
            // 是否显示弹出层
            open: false,
            openkehu: false, // 客户选择弹窗
            value: new Date(),
            list: [{
                mondayPrice: 0,
                tuesdayPrice: 0,
                wednesdayPrice: 0,
                thursdayPrice: 0,
                fridayPrice: 0,
                saturdayPrice: 0,
                sundayPrice: 0,
            }],
            // holiday_checked: [],
            checktable: [{}],
            checktableindex: 0,
            checklistteshutable: [{}],
            checklistteshutableindex: 0,
            radio: 0,
            mealList: [], // 套餐
            chargeItemsList: [], // 收费项
            configurationList: [], // 车型业务配置列表
            configurationquery: {
                pageNum: 1,
                pageSize: 10,
                modelName: null,
                configurationId: null
            },
            // 节假日
            holidayList: [], // 节假日列表
            holidayIds: [], // 选中的节假日id
            // 特殊日
            specialDayList: [], // 特殊日列表
        }
    },
    computed: {
        isEdit() {
            return !!this.form.planId;
        },
        rilijiage() {
            return {
                0: this.list[0].sundayPrice,
                1: this.list[0].mondayPrice,
                2: this.list[0].tuesdayPrice,
                3: this.list[0].wednesdayPrice,
                4: this.list[0].thursdayPrice,
                5: this.list[0].fridayPrice,
                6: this.list[0].saturdayPrice,
            }
        },
        /** 当前选中的节假日 */
        holiday_checked() {
            return this.holidayList.filter(val => this.holidayIds.indexOf(val.holidayId) >= 0)
        },
        checkboxlistdatepicker() {
            return this.holiday_checked.map(val => val.datepicker);
        },
        // 节假日/特殊日期费用费用(无值时传空集合)
        planHolidayBillingList() {
            const arr = [...this.holiday_checked, ...this.specialDayList];
            return map(arr, val => {
                return {
                    holidayId: val.holidayId, // 日期费用id(holidayType==1 必填)
                    holidayType: val.holidayId ? 1 : 2, // 费用类型（1节假日2特殊日期）
                    holidayName: val.label, // 日期名称
                    startTime: val.datepicker[0], // 开始时间（年月日）
                    endTime: val.datepicker[1], // 结束时间（年月日）
                    price: val.value || 0, // 费用
                }
            });
        },
        // 套餐信息
        planMealBillingList() {
            return map(this.mealList, val => {
                return {
                    mealId: val.mealId, // 套餐id
                    mealName: val.label, // 套餐名称
                    discount: val.value / 100 || 1,// 折扣取值0-1之间
                }
            });
        },
        // 费用项
        chargeItemsBillingList() {
            return map(this.chargeItemsList, val => {
                return {
                    chargeItemsName: val.chargeItemsName, // 收费项名称
                    uniquenessCode: val.uniquenessCode, // 收费项唯一编码
                    price: val.price || 0, // 费用
                }
            });
        },
        submitFormData() {
            // return {
            //     planId: this.planId, // 车价ID
            //     planName: this.planName, // 车价名称
            //     configurationId: this.configurationId, // 车型配置id
            //     isSetMeal: this.isSetMeal, // 是否有套餐（1是2否）
            //     planStandardBillingList: { // 基础费用
            //         sundayPrice: this.list[0].sundayPrice,  // 周日价格
            //         mondayPrice: this.list[0].mondayPrice,  // 周一价格
            //         tuesdayPrice: this.list[0].tuesdayPrice,  // 周二价格
            //         wednesdayPrice: this.list[0].wednesdayPrice,  // 周三价格
            //         thursdayPrice: this.list[0].thursdayPrice,  // 周四价格
            //         fridayPrice: this.list[0].fridayPrice,  // 周五价格注
            //         saturdayPrice: this.list[0].saturdayPrice,  // 周六价格
            //     },
            //     planHolidayBillingList: this.planHolidayBillingList, // 节假日/特殊日期费用费用(无值时传空集合)
            //     planMealBillingList: this.planMealBillingList, // 套餐信息
            //     chargeItemsBillingList: this.chargeItemsBillingList, // 费用项
            // };
            return {
                planId: this.planId, // 车价ID
                // configurationId: this.configurationId,
                // operatingClassification: this.operatingClassification,
                // modelConfig: String(this.modelConfig),
                // label: String(this.label),
                // deposit: this.deposit,
                // weeksPrice: this.weeksPrice,
                // weekendPrice: this.weekendPrice,
                // upcoverImage: this.upcoverImage,
                // detailsImage: this.detailsImage,
                planHolidayBillingList: this.planHolidayBillingList, // 节假日/特殊日期费用费用(无值时传空集合)
                // chargeItemsBillingList: this.chargeItemsBillingList, // 费用项
            }
        },
    },
    watch: {
        checkboxlistdatepicker: {
            handler(val) {
                this.checktableindex += 1;
            },
            deep: true
        },
        weeksPrice(val) {
            this.list[0].mondayPrice = val;
            this.list[0].tuesdayPrice = val;
            this.list[0].wednesdayPrice = val;
            this.list[0].thursdayPrice = val;
        },
        weekendPrice(val) {
            this.list[0].fridayPrice = val;
            this.list[0].saturdayPrice = val;
            this.list[0].sundayPrice = val;
        },
    },
    async mounted() {
        this.loading = true;
        await this.getholidayList(); // 获取节假日列表
        await this.getchargeItemsList(); // 获取收费项列表
        await this.getmealList(); // 获取套餐列表
        this.loading = false;
        if (this.planId) {
            console.log('走修改流程');
            await this.getData();
        }
        await this.getConfigurationList(); // 获取车型业务配置列表
    },
    methods: {
        checkModel(row) {
            this.showchexing = false;
            this.configurationId = row.configurationId;
            this.modelId = row.modelId;
            this.modelName = row.modelName;
            this.modelInfo = row.modelInfo;
            this.upcoverImage = row.upcoverImage;
            this.detailsImage = row.detailsImage;
        },
        //
        clearEdit() {
            this.specialDayList = [];
        },
        isEditaaaaaa(date) {
            const item = this.specialDayList.find(val => val.key == String([date, date]));
            return !!item
        },
        removeEdit(date) {
            _.remove(this.specialDayList, val => val.key == String([date, date]));
        },
        isShowEdit(data, date) {
            return data.isSelected && this.nowEdit == date.getTime();
            // return data.isSelected && this.nowEdit != date.getTime();
        },
        changeEdit(date) {
            this.nowPrice = this.superMmv(date, this.rilijiage[date.getDay()]);
            this.nowEdit = date.getTime();
        },
        okEdit(date) {
            this.nowEdit = null;
            this.prevEdit = date.getTime();
            // this.nowEdit = date.getTime();
            if (!this.nowPrice) return;
            this.addTeshuri(this.nowPrice, date, date);
        },
        //
        upcoverImageHandle(url) {
            console.log('----' + url)
            // 列表图片上传成功地址
            this.upcoverImage = url[0]
            // this.$refs['form'].validateField('upcoverImage')
        },
        updetailsImage(url) {
            // 详情封面上传成功地址
            this.detailsImage = url.join(',')
            // this.$refs['form'].validateField('detailsImage')
        },
        /** 获取车型业务配置列表 */
        async getConfigurationList() {
            const result = await planApi.configurationList(this.configurationquery);
            this.configurationList = result.rows || [];
            console.log(this.configurationList)
        },
        /** 获取节假日列表 */
        async getholidayList() {
            const result = await planApi.holidayList();
            this.holidayList = map(result.data, val => {
                return {
                    uuid: require('uuid').v4(),
                    label: val.holidayName,
                    value: val.price,
                    holidayId: val.holidayId,
                    holidayName: val.holidayName,
                    price: null,
                    datepicker: [val.startTime, val.endTime],
                }
            })
        },
        /** 获取收费项列表 */
        async getchargeItemsList() {
            const result = await planApi.chargeItemsList();
            this.chargeItemsList = result.data;
        },
        /** 获取套餐列表 */
        async getmealList() {
            const result = await planApi.mealList();
            console.log(result)
            this.mealList = result.data.map(val => {
                return {
                    uuid: require('uuid').v4(),
                    label: val.mealName,
                    value: val.discount,
                    mealId: val.mealId,
                }
            });
        },
        /** 新增特殊日 */
        addTeshuri(value = 0, start_time = new Date(), end_time = new Date()) {
            const item = this.specialDayList.find(val => val.key == String([start_time, end_time]));
            console.log(item);
            if (item) {
                item.value = value;
                return;
            }
            this.specialDayList.push({
                uuid: require('uuid').v4(),
                label: '特殊日',
                value: value,
                canEditLabel: true,
                canClose: true,
                datepicker: [start_time, end_time],
                key: String([start_time, end_time]),
            });
        },
        /** 移除特殊日 */
        onRemoveSpecialDay(item, index) {
            this.specialDayList.splice(index, 1);
        },
        /** 日历价格显示计算器 */
        superMmv(date, price) {
            // 计算出的价格
            let _price = price;
            function mmv(value) {
                return value;
                // const _date = new Date(value);
                // return new Date(_date.getFullYear(), _date.getMonth() + 1, _date.getDate()).getTime();
            }
            // 日历当前格子时间戳
            const time = mmv(date);
            // 遍历节假日数组
            require('lodash/forEach')(this.holiday_checked, val => {
                const start_time = mmv(val.datepicker[0]);
                const end_time = mmv(val.datepicker[1]);
                if (time <= end_time && time >= start_time) {
                    _price = val.value;
                }
            });
            // 遍历特殊日数组
            require('lodash/forEach')(this.specialDayList, val => {
                let start_time = mmv(val.datepicker[0]);
                let end_time = mmv(val.datepicker[1]);
                if (time <= end_time && time >= start_time) {
                    _price = val.value;
                }
            });
            return _price;
        },
        submitForm() {
            console.log(this.submitFormData)
            return this.submitFormData;
        },
        async getData() {
            this.loading = true;
            await planApi.getNewInfo(this.planId).then(response => {
                this.configurationId = response.data.configurationId;
                this.operatingClassification = response.data.operatingClassification;
                this.modelConfig = String(response.data.modelConfig).split(',');
                this.label = String(response.data.label).split(',');
                this.deposit = response.data.deposit;
                this.weeksPrice = response.data.weeksPrice;
                this.weekendPrice = response.data.weekendPrice;
                this.upcoverImage = response.data.upcoverImage;
                this.detailsImage = response.data.detailsImage;
                this.modelInfo = response.data.modelInfo;
                //
                // this.$refs.coverImage.previewToUrl(Utils.getImgUrl(response.data.upcoverImage));
                // this.$refs.detailsImage.previewToUrl(String(response.data.detailsImage.map(val => {
                //     return Utils.getImgUrl(val);
                // })));
                //
                // this.planName = response.data.planName; // 车价名称
                // this.modelInfo = response.data.modelInfo;
                // this.configurationId = response.data.configurationId; // 品牌车系车型
                // this.configurationquery.configurationId = response.data.configurationId;
                // 还原每周价格
                // this.list[0] = Object.assign(this.list[0], response.data.standardVo);
                // 还原收费项
                forEach(response.data.itemsVoList, val => {
                    const item = this.chargeItemsList.find(_val => _val.uniquenessCode == val.uniquenessCode);
                    if (item) {
                        item.price = val.price;
                    }
                });
                // 还原节假日/特殊日价格
                forEach(response.data.holidayVoList, val => {
                    // 还原节假日
                    if (val.holidayType == 1) {
                        this.holidayIds.push(val.holidayId);
                    } else {
                        // 还原特殊日
                        this.specialDayList.push({
                            uuid: require('uuid').v4(),
                            label: val.holidayName,
                            value: val.price,
                            holidayId: val.holidayId,
                            canClose: true,
                            datepicker: [new Date(val.startTime), new Date(val.endTime)],
                            key: String([new Date(val.startTime), new Date(val.endTime)]),
                        });
                    }
                });
                forEach(response.data.holidayVoList, val => {
                    const item = this.holiday_checked.find(_val => _val.holidayId == val.holidayId);
                    if (item) {
                        item.label = val.holidayName;
                        item.value = val.price;
                        item.datepicker = [new Date(val.startTime), new Date(val.endTime)];
                        item.key = String([new Date(val.startTime), new Date(val.endTime)]);
                    }
                });
                // 还原套餐车价
                this.isSetMeal = response.data.isSetMeal;
                forEach(response.data.mealVo, val => {
                    const item = this.mealList.find(_val => _val.mealId == val.mealId);
                    if (item) {
                        item.value = Math.floor(val.discount * 100);
                    }
                });
                this.loading = false;
            });
        },
        /** */
    },
}
</script>

<style>
#mmv-page .next {
    background: #f5f5f5;
}
#mmv-page .prev {
    background: #f5f5f5;
}

#mmv-page .el-calendar-day {
    padding: 0;
}

#mmv-page .next .rili-price-wrap {
    display: flex;
    align-items: center;
    padding: 5px 5px 0;
    color: #999;
    font-weight: bold;
    font-size: 16px;
    text-align: center;
    justify-content: center;
    white-space: nowrap;
}
</style>

<style lang="scss" scoped>
#mmv-page {
    ::v-deep .el-calendar-table .el-calendar-day {
        height: 60px;
    }
}
.rili {
    width: 100%;
    height: 100%;
    font-size: 12px;
}
.rili-wrap {
    position: relative;
}
.el-icon-refresh-left {
    position: absolute;
    top: 8px;
    right: 8px;
}
.aaaaaa {
    background: rgb(253, 226, 226);
}
.rili-day {
    color: #999;
}
.rili-price-wrap {
    display: flex;
    align-items: center;
    padding: 5px 5px 0;
    color: #409eff;
    font-weight: bold;
    font-size: 16px;
    text-align: center;
    justify-content: center;
    white-space: nowrap;
}
</style>
